﻿using System;
using System.Runtime.InteropServices;
using System.Net.Mime;
using System.IO;

namespace SBPweb.MediaCenter.Common.Resources
{
    public class FileHandler
    {

        [DllImport("urlmon.dll", CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = false)]
        internal static extern int FindMimeFromData(
            IntPtr pBC,
            [MarshalAs(UnmanagedType.LPWStr)] string pwzUrl,
            [MarshalAs(UnmanagedType.LPArray, ArraySubType=UnmanagedType.I1, SizeParamIndex=3)] byte[] pBuffer,
            int cbSize,
            [MarshalAs(UnmanagedType.LPWStr)] string pwzMimeProposed,
            int dwMimeFlags,
            out IntPtr ppwzMimeOut,
            int dwReserved);

        public static ContentType ReadMimeTypeFrom(FileInfo fileInfo, string mimeProposed)
        {

            FileStream fS = null;
            byte[] bytes = null;
            try
            {
                fS = new FileStream(fileInfo.FullName, FileMode.Open, FileAccess.Read);
                int length = (int)fS.Length;
                bytes = (byte[])Array.CreateInstance(typeof(byte), length);
                fS.Read(bytes, 0, length);
                fS.Close();
            }
            catch (IOException ex)
            {
                return null;
            }
            finally
            {
                if (fS != null)
                {
                    fS.Close();
                }
            }

            return ReadMimeTypeFrom(bytes, mimeProposed);
        }

        public static ContentType ReadMimeTypeFrom(byte[] dataBytes, string mimeProposed)
        {
            if (dataBytes == null)
            {
                throw new ArgumentNullException("dataBytes");
            }
            string mimeRet = String.Empty;
            IntPtr suggestPtr = IntPtr.Zero, filePtr = IntPtr.Zero, outPtr = IntPtr.Zero;
            if (mimeProposed != null && mimeProposed.Length > 0)
            {
                //suggestPtr = Marshal.StringToCoTaskMemUni(mimeProposed); // for your experiments ;-)
                mimeRet = mimeProposed;
            }
            int ret = FindMimeFromData(IntPtr.Zero, null, dataBytes, dataBytes.Length, mimeProposed, 0, out outPtr, 0);
            if (ret == 0 && outPtr != IntPtr.Zero)
            {
                //todo: this leaks memory outPtr must be freed
                return new ContentType(Marshal.PtrToStringUni(outPtr));
            }
            return new ContentType(mimeRet);
        }

    }
}
